
/**
 * storage的封装
 * storage.get()
 * storage.set()
 * storage.remove()
 * storage.has()
 * storage.session.....
 */
const storage = {};
//加方法
const extend = (s) => {
    return {
        set(key, value) {
            if (typeof value == "object") {
                s.setItem(key, JSON.stringify(value));
            } else {
                s.setItem(key, value);
            }
            if (value == undefined || value == null) {
                s.removeItem(key);
            }
        },
        get(key, isJson = true) {
            const item = s.getItem(key);

            try {
                if (isJson) {
                    let ret = JSON.parse(item);
                    //JSON.parse 可以转基本类型，不报错。。。，所以这里判断一下
                    if (typeof ret !== 'object') {
                        return undefined;
                    }

                    return ret;
                }
            } catch (e) {
                //解析出错,则证明不是json字符串，返回undefined
                return undefined;
            }
            return item;
        },
        has(key, isJson = false) {
            return !!(this.get(key, isJson));
        },
        remove: (key) => {
            s.removeItem(key);
        },
    };
};

Object.assign(storage, extend(window.localStorage));
Object.assign(storage, {
    session: extend(window.sessionStorage),
});

export default storage;


